package com.hm.fast.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author shishun.wang
 * @version 1.0
 * @date 2018/9/6 14:28
 * @describe
 */
@Slf4j
public class AES {

    public static String CRYPT_KEY = "def123efg8dv0abc";// 长度必须16位

    private static String AES = "AES";

    private AES() {

    }

    public static String encrypt(String content) {
        return encrypt(content, CRYPT_KEY);
    }

    public static String encrypt(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance(AES);
            SecretKeySpec securekey = new SecretKeySpec(password.getBytes(), AES);
            cipher.init(Cipher.ENCRYPT_MODE, securekey);

            byte[] bytes = cipher.doFinal(content.getBytes());
            return byte2hex(bytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static String decrypt(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance(AES);
            SecretKeySpec securekey = new SecretKeySpec(password.getBytes(), AES);
            cipher.init(Cipher.DECRYPT_MODE, securekey);

            byte[] bytes = cipher.doFinal(hex2byte(content.getBytes()));
            return new String(bytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static String decrypt(String content) {
        return decrypt(content, CRYPT_KEY);
    }

    /***
     * 二进制转十六进制字符串
     *
     * @param bytes
     * @return
     */
    private static String byte2hex(byte[] bytes) {
        String result = "";
        String temp = "";
        for (int i = 0; i < bytes.length; i++) {
            temp = (Integer.toHexString(bytes[i] & 0XFF));
            if (temp.length() == 1)
                result = result + "0" + temp;
            else
                result = result + temp;
        }
        return result.toUpperCase();
    }

    private static byte[] hex2byte(byte[] bytes) {
        if ((bytes.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] bys = new byte[bytes.length / 2];
        for (int i = 0; i < bytes.length; i += 2) {
            String item = new String(bytes, i, 2);
            bys[i / 2] = (byte) Integer.parseInt(item, 16);
        }
        return bys;
    }
}
